package com.itbaizhan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/*获取请求头信息
获取请求头信息
req.getHeader("headerKey")
根据请求头中的key获取对应的value。
String headerValue = req.getHeader("headerKey");
req.getHeaderNames()

获取请求头中所有的key，该方法返回枚举类型。
Enumeration<String> headerNames = req.getHeaderNames();*/
public class GetRequestHeaderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //指定的key获取请求头信息
        String headerInfo =req.getHeader("Accept-Encoding");

        //获取请求头中的所有数据
        Enumeration<String> headerNames = req.getHeaderNames();

        PrintWriter pw = resp.getWriter();
        pw.println("Header Info - Accept-Encoding: "+headerInfo);

        while (headerNames.hasMoreElements()){
            //获取key的值
           String key =  headerNames.nextElement();
           //将key放进getHeader中，
           String value = req.getHeader(key);
           pw.println(key+" : "+value);
        }
        pw.flush();
        pw.close();
    }
}
